package su.msk.jet.team01.chatik.server.data;

import java.util.HashMap;
import java.util.Map;

import su.msk.jet.team01.chatik.server.exception.InvalidRoomNameException;

public class RoomManager {
	private static final String EXCEPTION_MSG_INVALID_ROOM_NAME = "Invalid room name specified";
	private Map<String, Room> rooms = new HashMap<String, Room>();
	private Room defaultRoom = createRoom("All");

	protected RoomManager() {
		
	}
	
	public Room getDefaultRoom() {
		return defaultRoom;
	}

	public Room getRoom(final String name) throws InvalidRoomNameException {
		Room room;

		if (name.isEmpty()) {
			throw new InvalidRoomNameException(EXCEPTION_MSG_INVALID_ROOM_NAME);
		}

		synchronized (rooms) {
			room = rooms.get(name);

			if (room == null) {
				room = createRoom(name);
			}
			return room;
		}
	}

	public Map<String, Room> getRooms() {
		synchronized (rooms) {
			return new HashMap<String, Room>(rooms);
		}
	}

	public void removeRoom(final String name) {
		Room room;

		synchronized (rooms) {
			room = rooms.get(name);
			if (room != null && room.getClients().isEmpty() && room != defaultRoom) {
				rooms.remove(room.getName());
			}
		}
	}

	private Room createRoom(final String name) {
		Room room;

		synchronized (rooms) {
			room = new Room(name);
			rooms.put(name, room);
		}
		return room;
	}

}
